/**
 *
 * @param {String} url - Http地址
 * @returns {Object} 值对象
 */
function GetUrlParams(url) {
  // 创建 URL 对象
  const parsedUrl = new URL(url);
  // 获取查询字符串部分并解码
  const queryString = decodeURIComponent(parsedUrl.search);
  // 创建 URLSearchParams 对象(使用的是encodeURIComponent加码)
  const params = new URLSearchParams(queryString);
  //返回Object对象
  return Object.fromEntries(params);
}

//获取url参数
export function GetQueryString(name) {
  let reg = new RegExp("[?&]" + name + "=([^&]*)(&?)", "i");
  let r = window.location.href.substr(1).match(reg);
  if (r != null) return unescape(r[1]);
  return null;
}

//Querystring
export function ObjToQuerystring1(obj) {
  return qs.stringify(obj);
}
export function ObjToQuerystring2(obj) {
  const params = new URLSearchParams(obj);
  const queryString = params.toString();
  return queryString;
}
export function ObjToQuerystring3(data) {
  const formData = [];
  Object.keys(data).forEach((key) => {
    formData.push(
      encodeURIComponent(key) + "=" + encodeURIComponent(data[key])
    );
  });
  return formData.join("&");
}
//Querystring转对象
export function QuerystringToObj(queryString) {
  return qs.parse(queryString);
}
export function QuerystringToObj1(queryString) {
  //Url字符(URLSearchParams使用的是encodeURIComponent加码)
  //const queryString = "a=1&b=2";
  return Object.fromEntries(new URLSearchParams(queryString));
}

//下载文件
function downloadURI(uri, name) {
  var link = document.createElement("a");
  link.download = name;
  link.href = uri;
  link.click();
}
function downloadUrl(url) {
  window.open(url, "_self");
  //window.location.href = url
}

/**
 * 获取地址栏 URL 的查询字符串的键/值对象
 * =============================================================
 * @returns {{}|null}
 */
export const getURLQuery = () => {
  let url = location.search;
  const query = {};

  if (!url.includes("?")) {
    return null;
  }

  url = url.replace(/^\?/, "");

  if (url.split("&").length < 1) {
    const arr = url.split("=");

    // 没有任何 url 查询参数
    if (arr.length < 1) {
      return null;
    }

    // 只有一个 URL 查询参数
    query[arr[0]] = decodeURIComponent(arr[1]);

    return query;
  }

  // 有多个 URL 查询参数
  url.split("&").forEach((str) => {
    const arr = str.split("=");

    query[arr[0]] = decodeURIComponent(arr[1]);
  });

  return query;
};



/**
 * 将 URL 的 search 部分，转化成单体对象
 * ======================================
 * @returns {null}
 */
export const getQuery = () => {
  let url = location.search
  let query = {}

  if (url.indexOf('?') < 0) {
    return null
  }

  url = url.replace(/^\?/, '')

  if (url.split('&').length < 1) {
    let arr = url.split('=')

    // 没有任何 url 查询参数
    if (arr.length < 1) {
      return null
    }

    // 只有一个 URL 查询参数
    query[arr[0]] = decodeURIComponent(arr[1])

    return query
  }

  // 有多个 URL 查询参数
  url.split('&').forEach(str => {
    let arr = str.split('=')

    query[arr[0]] = decodeURIComponent(arr[1])
  })

  return query
}

/**
 * 获取 URL 地址中某个 query 字段的值
 * =============================================================
 * @param name
 * @param url
 * @returns {*}
 */
export const getURLQueryParamByName = (name, url) => {
  let regex;
  let results;

  if (!url) {
    url = window.location.href;
  }

  name = name.replace(/[[]]/g, "\\$&");
  regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)");
  results = regex.exec(url);

  if (!results) {
    return null;
  }

  if (!results[2]) {
    return "";
  }

  return decodeURIComponent(results[2].replace(/\+/g, " "));
};

/**
 * 将 URL 地址转化为对象
 * ======================================
 * @param url
 * @returns {{protocol: *, pathname: *, path: *, query: *, hash: *}}
 */
export const parseURL = (url) => {
  const pattern =
    /^(?<protocol>[^:/?#]+):\/\/(?<domain>[^/?#]*)(?<path>[^?#]*)\\?(?<query>[^#]*)#(?<fragment>.*)/;
  const matches = url.match(pattern);

  return {
    protocol: matches[1],
    pathname: matches[2],
    path: matches[3],
    query: matches[4],
    hash: matches[5],
  };
};

/**
 * 校验是否为有效的 URL 地址
 * ======================================
 * @param str
 * @returns {boolean}
 */
export const isValidUrl = str => {
  let pattern = new RegExp(
    '^(https?:\\/\\/)?' + // protocol
    '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // domain name
    '((\\d{1,3}\\.){3}\\d{1,3}))' + // OR ip (v4) address
    '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' + // port and path
    '(\\?[;&a-z\\d%_.~+=-]*)?' + // query string
      '(\\#[-a-z\\d_]*)?$',
    'i'
  ) // fragment locator

  return !!pattern.test(str)
}

//校验Url http https
function IsValidHttpUrl(string) {
  let url;
  try {
    url = new URL(string);
  } catch (_) {
    return false;
  }
  return url.protocol === "http:" || url.protocol === "https:";
}


/**
 * 获取 URL 地址中某个 query 字段的值
 * ======================================
 * @param name
 * @param url
 * @returns {*}
 */
export const getParameterByName = (name, url) => {
  let regex
  let results

  if (!url) {
    url = window.location.href
  }

  name = name.replace(/[[]]/g, '\\$&')
  regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)')
  results = regex.exec(url)

  if (!results) {
    return null
  }

  if (!results[2]) {
    return ''
  }

  return decodeURIComponent(results[2].replace(/\+/g, ' '))
}


//URLSearchParams
function URLSearchParams() {
  var str = "http://www.domain.com/?user=Alan&id=123&id=456";
  var searchParams = new URLSearchParams(str);
  // let...of 语法（迭代对象）
  for (let p of searchParams) {
    // console.log(p);
  }
  /*
   * URLSearchParams.append()
   * @添加新的key/value到URL中
   */
  searchParams.append("city", encodeURIComponent("深圳"));

  /*
   * URLSearchParams.has()
   * @查询是否存在,返回一个boolean值
   */
  searchParams.has("id"); // true
  /*
   * URLSearchParams.get()
   * @返回相关联的第一个值
   */
  searchParams.get("id"); // 123

  /*
   * URLSearchParams.getAll()
   * @返回所有相同key的值
   */
  searchParams.getAll("id"); // ["123", "456"]

  /*
   * URLSearchParams.set()
   * @设置key的value值,如果有多个,删除其他的
   */
  searchParams.set("id", "789");

  /*
   * searchParams.delete()
   * @删除所有参数列表key与value值,重复的key都被删除
   */
  searchParams.delete("id");

  /*
   * searchParams.entries()
   * @返回所有键值对key/value
   */
  for (let pair of searchParams.entries()) {
    console.log(pair[0] + ", " + pair[1]);
  }

  /*
   * searchParams.keys()
   * @返回所有键key
   */
  for (let key of searchParams.keys()) {
    console.log(key);
  }

  /*
   * searchParams.values()
   * @返回所有值
   */
  for (let value of searchParams.values()) {
    console.log(value);
  }

  /*
   * searchParams.toString()
   * @返回修改过的URL
   */
  searchParams.toString();
  console.log(searchParams.toString());
}
